package com.example.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.controller.utils.Result;
import com.example.domain.Book;
import com.example.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 加入了消息一致性异常处理后
 * @RestController等价于@Controller+@@ResponseBody返回JSON数据
 */
@RestController
@RequestMapping("/books")
public class BookController02 {

    @Autowired
    private IBookService bookService;

    @GetMapping
    public Result getAll(){
        return new Result(true, bookService.list());
    }

    //请求方式为Post
    @PostMapping
    public Result save(@RequestBody Book book) throws IOException {

        if (book.getName().equals("123") ) throw new IOException();
        boolean flag = bookService.save(book);
        return new Result(flag, flag ? "添加成功^_^" : "添加失败-_-!");
    }

    @PutMapping
    public Result update(@RequestBody Book book) throws IOException {
        if (book.getName().equals("123") ) throw new IOException();
        boolean flag = bookService.updateById(book);
        return new Result(flag, flag ? "修改成功^_^" : "修改失败-_-!");
    }
    /*  使用路径变量传参：http://localhost/books/2  */
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Integer id){
        return new Result(bookService.removeById(id));
    }

    @GetMapping("{id}")
    public Result getById(@PathVariable Integer id){
        return new Result(true, bookService.getById(id));
    }

    @GetMapping("{currentPage}/{pageSize}")
    public Result getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book){
//        System.out.println("参数==>"+book);

        IPage<Book> page = bookService.getPage01(currentPage, pageSize,book);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if( currentPage > page.getPages()){
            page = bookService.getPage01((int)page.getPages(), pageSize,book);
        }
        return new Result(true, page);
    }
    /*//图书借阅功能实现
    public*/

}

















